import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { APP_LOGO, APP_NAME } from '@conf'
import { useMessage } from '@hooks/useAppMessage'
import { useSessionStorage } from '@hooks/useSessionStorage'
import { useLoginMutation } from '@services/auth'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { Button, Checkbox, Flex, Form, Input } from 'antd'
import { useEffect } from 'react'

const LOGIN_KEY = 'login:token'
const LOGIN_EXPIRED_IN = 7 * 24 * 60 * 60 * 1000 // 7天后过期

function rememberInfo(values, remember) {
  const data = {
    remember,
    username: values.username, // 保存用户名字段
    expired_at: Date.now() + LOGIN_EXPIRED_IN,
  }
  // 7天后过期
  sessionStorage.setItem(LOGIN_KEY, window.btoa(JSON.stringify(data)))
}

export const Route = createFileRoute('/login')({
  component: RouteComponent,
})

function RouteComponent() {
  const navigate = useNavigate()
  const message = useMessage()

  const { mutate } = useLoginMutation()
  const [token, setToken] = useSessionStorage('token', null)
  const [, setAdmin] = useSessionStorage('admin')

  const handleLogin = async (values, remember) => {
    console.log('%c Line:25 🥛 values, remember', 'color:#2eafb0', values, remember)
    mutate(values, {
      onSuccess: (resp) => {
        console.log('%c Line:42 🌭 resp', 'color:#b03734', resp)
        if (200 !== resp.code) {
          message.error(resp.msg)
          return
        }

        const { token, admin } = resp.data
        setAdmin(admin)
        setToken(token)
        remember && rememberInfo(values, remember)

        message.success('登录成功')
        setTimeout(() => navigate({ to: '/' }), 1200)
      },
      onError: (error) => {
        console.log('%c Line:52 🥕 error', 'color:#ea7e5c', error)
        const { errors } = error.response?.data
        if (errors) {
          for (const key in errors) {
            const item = errors[key]
            message.error(item.join(','))
          }
        }
      },
    })
  }

  useEffect(() => {
    const res = sessionStorage.getItem(LOGIN_KEY)
    console.log('%c Line:58 🍯 res', 'color:#ffdd4d', res)
    if (!res) return

    const values = JSON.parse(window.atob(res))
    if (values && values.expired_at > Date.now()) {
      handleLogin(values)
    }
  }, [])

  useEffect(() => {
    token && navigate({ to: '/' })
  }, [token])

  const onFinish = ({ username, password, remember }) => {
    handleLogin({ username, password }, remember)
  }
  const onFinishFailed = (errorInfo) => console.log(errorInfo, 'onFailed')

  return (
    <div className="w-screen h-screen overflow-hidden grid place-items-center bg-[#f0f0f0]">
      <div className="flex flex-col items-center justify-center w-full h-full">
        <div className="login-header text-conter">
          <div className="flex justify-center items-center">
            <img className="w-40 aspect-[2/1]" src={APP_LOGO} alt="logo" />
          </div>
          <div className="mt-5 mb-7 text-[#121213] font-bold">{APP_NAME}</div>
        </div>
        <div className="login-body">
          <Form
            name="login"
            style={{ width: 320 }}
            initialValues={{ remember: false }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off">
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入用户名!' }]}
              autoComplete="off">
              <Input size="large" prefix={<UserOutlined />} placeholder="用户名" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码!' }]}
              autoComplete="off">
              <Input size="large" prefix={<LockOutlined />} type="password" placeholder="密码" />
            </Form.Item>
            <Form.Item>
              <Flex justify="space-between" align="center">
                <Form.Item name="remember" valuePropName="checked" noStyle>
                  <Checkbox>
                    <span className="text-[#444A57]">自动登录</span>
                  </Checkbox>
                </Form.Item>
                <a href="">忘记密码？</a>
              </Flex>
            </Form.Item>

            <Form.Item>
              <Button block type="primary" htmlType="submit">
                登 录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  )
}
